package com.charlessong.unionpay.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.charlessong.unionpay.properties.AliPayProperties;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author charles
 * @Date 2021/11/18
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/notify")
public class NotifyController {

    private AliPayProperties aliPayProperties;

    @SneakyThrows
    @RequestMapping("/alipay")
    public String alipay(HttpServletRequest request){
        //获取支付宝POST过来反馈信息
        Map< String , String > params = new HashMap< String , String >();
        Map requestParams = request.getParameterMap();
        for(Iterator iter = requestParams.keySet().iterator(); iter.hasNext();){
            String name = (String)iter.next();
            String[] values = (String [])requestParams.get(name);
            String valueStr = "";
            for(int i = 0;i < values.length;i ++ ){
                valueStr =  (i==values.length-1)?valueStr + values [i]:valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put (name,valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean flag = AlipaySignature.rsaCheckV1 (params,aliPayProperties.getAliPublicKey(), "utf-8","RSA2");
        log.info("========>>>> 参数校验结果：{}",flag);
        log.info("========>>>> 支付宝异步通知参数为：\n{}",params);
        return "success";
    }
}
